'''
# Coding:utf-8
# Project: iiop
# Author: rtf
# Time: 2024-06-25 10:56:23
# FileName: read_images.py
# Software: PyCharm
'''

import os
import datetime
import random
from docx import Document
from pathlib import Path


def extract_images_with_positions(doc):
    # 获取当前脚本所在目录
    current_dir = Path(__file__).resolve().parent
    # 获取项目根目录（假设项目根目录与当前脚本目录同级）
    project_root = current_dir.parent

    current_date = datetime.datetime.now().strftime('%Y%m%d')
    output_folder = os.path.join(f"{project_root}/download/{current_date}")
    # 检查输出文件夹是否存在，如果不存在则创建
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 初始化图片计数
    image_count = 0
    image_positions = []

    current_time = datetime.datetime.now().strftime("%H%M%S")
    # 遍历文档中的段落
    for i, para in enumerate(doc.paragraphs):
        for j, run in enumerate(para.runs):
            if run.element.xpath('.//a:blip'):
                for blip in run.element.xpath('.//a:blip'):
                    random_number = random.randint(10000, 99999)
                    random_str = f"{current_time}{random_number}"

                    image_count += 1
                    image = doc.part.related_parts[
                        blip.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed')]
                    image_filename = os.path.join(output_folder, f'image_{image_count}_{random_str}.png')

                    # 将图片保存到本地
                    with open(image_filename, 'wb') as img_file:
                        img_file.write(image.blob)

                    # 记录图片位置
                    image_positions.append({
                        'image_filename': f"/download/{current_date}/image_{image_count}_{random_str}.png",
                        'paragraph_index': i,
                        'run_index': j
                    })

    # 遍历文档中的表格
    for table_index, table in enumerate(doc.tables):
        for row_index, row in enumerate(table.rows):
            for cell_index, cell in enumerate(row.cells):
                for para_index, para in enumerate(cell.paragraphs):
                    for run_index, run in enumerate(para.runs):
                        if run.element.xpath('.//a:blip'):
                            for blip in run.element.xpath('.//a:blip'):
                                image_count += 1
                                image = doc.part.related_parts[blip.get(
                                    '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed')]
                                image_filename = os.path.join(output_folder, f'image_{image_count}.png')

                                # 将图片保存到本地
                                with open(image_filename, 'wb') as img_file:
                                    img_file.write(image.blob)

                                # 记录图片位置
                                image_positions.append({
                                    'image_filename': f"/download/{datetime.datetime.now().strftime('%Y%m%d')}/image_{image_count}.png",
                                    'table_index': table_index,
                                    'row_index': row_index,
                                    'cell_index': cell_index,
                                    'paragraph_index': para_index,
                                    'run_index': run_index
                                })

    print(f"{image_count} images extracted and saved to '{output_folder}'")
    return image_positions


# 示例调用
# docx_path = '/home/rtf/Project/Jna/iiop/download/20240624/上线前贯通测试（软硬件购置及开发实施模板）.docx'
# doc = Document(docx_path)
#
# positions = extract_images_with_positions(doc)

# 输出图片位置
# for pos in positions:
#     print(pos)
